#include<bits/stdc++.h>
using namespace std;
const int MAXN=10010,MAXM=50010;
int n,m,ans=-1,DFN[MAXN],Low[MAXN],belong[MAXN],cnt,_time,vis[MAXN],head[2][MAXN],eout[MAXN],siz[MAXN];
struct edge
{
	int u,v,next;
}e[MAXM*2];
stack<int> S;
void addedge(int i,int *head,int u,int v)
{
	e[i]=(edge){u,v,head[u]};
	head[u]=i;
}
void Tarjan(int u)
{
	int v;
	DFN[u]=Low[u]=++_time;
	S.push(u);
	vis[u]=true;
	for(int i=head[0][u];i;i=e[i].next)
	{
		v=e[i].v;
		if(!DFN[v])
		{
			Tarjan(v);
			Low[u]=min(Low[u],Low[v]);
		}
		else if(vis[v])
		{
			Low[u]=min(Low[u],DFN[v]);
		}
	}
	if(DFN[u]==Low[u])
	{
		++cnt;
		do
		{
			v=S.top();
			S.pop();
			vis[v]=false;
			belong[v]=cnt;
			++siz[cnt];
		}while(u!=v);
	}
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;++i)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		addedge(i,head[0],x,y);
	}
	for(int i=1;i<=n;++i)
		if(!DFN[i])Tarjan(i);
	for(int i=1;i<=m;++i)
	{
		int x=belong[e[i].u],y=belong[e[i].v];
		if(x!=y)
		{
			addedge(i+m,head[1],x,y);
			++eout[x];
		}
	}
	for(int i=1;i<=cnt;++i)
		if(!eout[i])ans=~ans?0:siz[i];
	printf("%d\n",ans);
	return 0;
}
